//
//  WitnessSamplesViewController.m
//  Estate
//
//  Created by wangdongdong on 16/9/1.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define DIC_DATE @"date"
#define CELL_HEIGHT 46.0f


#import "WitnessSamplesViewController.h"
#import "WitnessSamplesDetailVC.h"
#import "AddJLQYViewController.h"
#import "SampleProcessModel.h"
#import "NewInspectionTextCell.h"

@interface WitnessSamplesViewController ()<UITableViewDelegate,UITableViewDataSource>

//表格
@property(strong, nonatomic)UITableView *tableView;
//数据
@property(strong ,nonatomic)NSMutableArray *dataArray;
//添加按钮
@property (strong, nonatomic)UIButton *addBtn;

@end

@implementation WitnessSamplesViewController

-(NSMutableArray *)dataArray{
    if(_dataArray==nil){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView {
    
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-44-49-50*BIZ)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
        _tableView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
        [_tableView registerNib:[UINib nibWithNibName:@"NewInspectionTextCell" bundle:nil] forCellReuseIdentifier:@"detail"];
    }
    return _tableView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self createView1];
    [self initDataSource];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadGJList) name:@"witness" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadGJList) name:@"reloadData" object:nil];
}

-(void)reloadGJList {
    [self.dataArray removeAllObjects];
    [self initDataSource];
    [self.tableView reloadData];
}

//创建添加btn
- (void)createView1 {
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    self.addBtn=[[UIButton alloc]initWithFrame:CGRECTS(260, 360, 100, 100)];
    [_addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [_addBtn addTarget:self action:@selector(clickAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_addBtn];
}

// 添加事件
- (void)clickAddBtn {
    AddJLQYViewController *addGJVC = [[AddJLQYViewController alloc] init];
    [self.navigationController pushViewController:addGJVC animated:YES];
}
// 初始化数据
- (void)initDataSource
{
    // 清空数据源
    [self.dataArray removeAllObjects];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result = [db executeQuery:SQL_SAMPLE_PROCESS_SELECT_JL(PROID, USERID)];
    
    NSMutableDictionary *dic;
    while ([result next]) {
        //查询到 年
        NSString* year= [result stringForColumn:@"year"];
        //查询到月
        NSString *month =[result stringForColumn:@"month"] ;
        /*
         * 根据日期查询展开的数据
         */
        NSString *sqlStr = [NSString stringWithFormat:@"SELECT *, substr(CREATE_TIME,1,4) as YEAR, substr(CREATE_TIME,6,2) as MONTH, substr(CREATE_TIME,9,2) as DAY FROM SAMPLE_PROCESS WHERE YEAR = '%@' AND MONTH = '%@' AND PRO_ID='%@' AND SAMPLE_WINESS_USER = '%@' AND ID IN (SELECT PROCESS_ID FROM SAMPLE_PROCESS_RECORD) ORDER BY CREATE_TIME desc", year, month, PROID, USERID];
        FMResultSet *results=[db executeQuery:sqlStr];
        //查询到记录
        NSMutableArray *DetailArr=[NSMutableArray array];
        while ([results next]) {
            SampleProcessModel *spModel = [[SampleProcessModel alloc] init];
            
            spModel.ID = [results stringForColumn:@"ID"];
            spModel.PRO_ID = [results stringForColumn:@"PRO_ID"];
            spModel.SAMPLE_NUMBER = [results stringForColumn:@"SAMPLE_NUMBER"];
            spModel.SAMPLE_GET_TIME = [results stringForColumn:@"SAMPLE_GET_TIME"];
            spModel.SAMPLE_GET_ADDRESS = [results stringForColumn:@"SAMPLE_GET_ADDRESS"];
            spModel.SAMPLE_GET_ADDRESS_INFO = [results stringForColumn:@"SAMPLE_GET_ADDRESS_INFO"];
            spModel.SAMPLE_WINESS_USER = [results stringForColumn:@"SAMPLE_WINESS_USER"];
            spModel.SAMPLE_QR_CODE = [results stringForColumn:@"SAMPLE_QR_CODE"];
            spModel.SAMPLE_PROCESS_STATE = [results stringForColumn:@"SAMPLE_PROCESS_STATE"];
            spModel.EXTEND_INFO = [results stringForColumn:@"EXTEND_INFO"];
            spModel.CREATE_USER_NAME = [results stringForColumn:@"CREATE_USER_NAME"];
            spModel.CREATE_TIME = [results stringForColumn:@"CREATE_TIME"];
            spModel.CREATE_IP = [results stringForColumn:@"CREATE_IP"];
            spModel.MODIFY_USER_NAME = [results stringForColumn:@"MODIFY_USER_NAME"];
            spModel.MODIFY_TIME = [results stringForColumn:@"MODIFY_TIME"];
            spModel.MODIFY_IP = [results stringForColumn:@"MODIFY_IP"];
            spModel.day = [results stringForColumn:@"DAY"];
            [DetailArr addObject:spModel];
        }
        //查询到数量
        NSString *counts=[result stringForColumn:@"COUNT(*)"];
        //拼接成标题
        NSString *tiemAndCount = [NSString stringWithFormat:@"%@年%@月 (%@条)", year, month, counts];
        //创建一个字典 包含数组，分组名，是否展开的标示
        dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:DetailArr, DIC_ARARRY, tiemAndCount, DIC_TITILESTRING, [NSNumber numberWithInt:0], DIC_EXPANDED, nil];
        //将字典加入数组
        [self.dataArray addObject:dic];
    }
    [db close];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic=[_dataArray objectAtIndex:section];
    
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    SampleProcessModel *spModel = array[indexPath.row];
    
    NewInspectionTextCell *cell=[NewInspectionTextCell cellWithTableView:tableView];
    // 列表标题
    cell.gengduo.hidden=YES;

    NSString *titleStr = [NSString stringWithFormat:@"%@日_%@_见证取样工作", spModel.day, spModel.SAMPLE_NUMBER];
    cell.title.text = titleStr;
    cell.title.numberOfLines = 0;
    cell.textLabel.font = [UIFont systemFontOfSize:16.*BIZ];
    cell.state.textColor = UIColorFromRGB(0x549587);
    
    if ([spModel.SAMPLE_PROCESS_STATE isEqualToString:@"1"]) {
        cell.state.text = @"待检验";
        
    } else if ([spModel.SAMPLE_PROCESS_STATE isEqualToString:@"2"]) {
        cell.state.text = @"防伪通过";
        
    } else if ([spModel.SAMPLE_PROCESS_STATE isEqualToString:@"3"]) {
        cell.state.text = @"防伪不通过";

    }
    return cell;
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    [eButton setTitle:[[_dataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:14.];
    
    //设置button的图片和标题的相对位置
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    UIImage *image = eButton.imageView.image;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, image.size.width)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0, eButton.titleLabel.bounds.size.width+20, 0, -eButton.titleLabel.bounds.size.width)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[_dataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 10;
    }else{
        return 0;
    }
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70 * BIZ;
}


#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WitnessSamplesDetailVC *jzqyVC=[[WitnessSamplesDetailVC alloc]init];
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    SampleProcessModel *spModel = array[indexPath.row];
    jzqyVC.jl=@"";
    jzqyVC.spModel = spModel;
    [self.navigationController pushViewController:jzqyVC animated:YES];
}


#pragma mark -- 内部调用
//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[_dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

//返回指定节是否是展开的

-(int)isExpanded:(long)section{
    NSDictionary *dic=[_dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end




